﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tasker.Composition;
using Tasker.Infrastructure.Entities;
using Tasker.Infrastructure.Repositories;
using Tasker.Infrastructure.Repositories.Base;
using Tasker.Repositories.Entities;

namespace Tasker.Repositories
{
    class UserEmailsRepositoryEF: IUserEmailsRepository
    {
        private EntitiesContext _context = Resolver.Resolve<EntitiesContext>();
        private IContextManager _manager = Resolver.Resolve<IContextManager>();

        public IUserEmail SelectById(int id)
        {
            return _context.UserEmails.SingleOrDefault(ue => ue.Id == id);
        }

        public IEnumerable<IUserEmail> SelectByUserId(int userId)
        {
            return _context.UserEmails.Where(ue => ue.UserId == userId);
        }

        public void DeleteAll(int userId)
        {
            IEnumerable<UserEmail> userEmails = _context.UserEmails.Where(ue => ue.UserId == userId);
            foreach (UserEmail userEmail in userEmails)
            {
                _context.UserEmails.DeleteObject(userEmail);
            }
        }

        public IEnumerable<IUserEmail> SelectAll()
        {
            return _context.UserEmails.ToList();
        }

        public void Update(IUserEmail entity)
        {
            UserEmail res = _context.UserEmails.SingleOrDefault(ue => ue.Id == entity.Id);

            res.Email = entity.Email;
            res.UserId = entity.UserId;

            _manager.Save();
        }

        public IUserEmail Create()
        {
            return new UserEmail();
        }

        public void Delete(IUserEmail entity)
        {
            UserEmail userEmail = _context.UserEmails.SingleOrDefault(ue => ue.Id == entity.Id);
            _context.UserEmails.DeleteObject(userEmail);
        }

        public IUserEmail Insert(IUserEmail entity)
        {
            UserEmail res = entity as UserEmail;
            _context.UserEmails.AddObject(res);
            _manager.Save();
            return res;
        }
    }
}
